import { SessionConfigManager } from './session-config-manager'
import { createHash } from 'crypto'
import * as path from 'path'
import * as os from 'os'

export interface AutoSessionContext {
  workingDirectory?: string
  userHome?: string
  userName?: string
  projectName?: string
}

export class AutoSessionManager {
  private static sessionCache = new Map<string, SessionConfigManager>()

  /**
   * 自动检测用户环境并获取会话管理器
   */
  static async getSessionManager(context?: AutoSessionContext): Promise<SessionConfigManager> {
    const sessionKey = this.generateSessionKey(context)
    
    // 从缓存获取
    if (this.sessionCache.has(sessionKey)) {
      const manager = this.sessionCache.get(sessionKey)!
      await manager.loadConfig()
      return manager
    }

    // 创建新的会话管理器
    const { userId, projectPath } = this.extractUserInfo(context)
    const manager = new SessionConfigManager(undefined, userId, projectPath)
    await manager.loadConfig()
    
    // 缓存管理器
    this.sessionCache.set(sessionKey, manager)
    
    return manager
  }

  /**
   * 生成会话缓存键
   */
  private static generateSessionKey(context?: AutoSessionContext): string {
    const workingDir = context?.workingDirectory || process.cwd()
    const userHome = context?.userHome || os.homedir()
    const userName = context?.userName || os.userInfo().username
    
    return createHash('md5')
      .update(`${userName}-${userHome}-${workingDir}`)
      .digest('hex')
      .substring(0, 16)
  }

  /**
   * 提取用户信息
   */
  private static extractUserInfo(context?: AutoSessionContext): {
    userId: string
    projectPath: string
  } {
    const workingDir = context?.workingDirectory || process.cwd()
    const userName = context?.userName || os.userInfo().username
    const projectName = context?.projectName || path.basename(workingDir)

    return {
      userId: `${userName}@${os.hostname()}`,
      projectPath: workingDir
    }
  }

  /**
   * 智能检测项目信息
   */
  static detectProjectInfo(context?: AutoSessionContext): {
    userId: string
    projectPath: string
    projectName: string
    sessionId: string
  } {
    const workingDir = context?.workingDirectory || process.cwd()
    const userName = context?.userName || os.userInfo().username
    const projectName = context?.projectName || path.basename(workingDir)
    const sessionKey = this.generateSessionKey(context)

    return {
      userId: `${userName}@${os.hostname()}`,
      projectPath: workingDir,
      projectName,
      sessionId: sessionKey
    }
  }

  /**
   * 清理会话缓存
   */
  static clearCache(): void {
    this.sessionCache.clear()
  }

  /**
   * 获取缓存状态
   */
  static getCacheStatus(): {
    cacheSize: number
    sessions: Array<{
      sessionKey: string
      sessionId: string
      userId?: string
      projectPath?: string
    }>
  } {
    const sessions = Array.from(this.sessionCache.entries()).map(([key, manager]) => ({
      sessionKey: key,
      sessionId: manager.getSessionId(),
      userId: manager.getSessionInfo().userId,
      projectPath: manager.getSessionInfo().projectPath
    }))

    return {
      cacheSize: this.sessionCache.size,
      sessions
    }
  }
}
